import 'dart:convert';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_bluetooth/flutterbluetooth.dart';
import 'package:flutter_bluetooth/BluetoothMsg.dart';
import 'package:flutterbluetooth_example/toast.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import 'bluetooth_button.dart';



void main() {
  runApp(MaterialApp(
    home: MyApp(),));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  BluetoothNotifier bluetoothNotifier;
  BluetoothListNotifier bluetoothListNotifier;

  @override
  void initState() {
    super.initState();
    requestPermission();

    bluetoothNotifier = BluetoothNotifier(null, null);
    bluetoothListNotifier = BluetoothListNotifier();
   initBluetooth();
  }

  initBluetooth() async {
    bluetoothNotifier.bluetoothState = await FlutterBluetooth.blueState;
    FlutterBluetooth.initReceiver(
      receiveBtReadMsg: receiveBtReadMsg,
      receiveBtState: receiveBtState,
      receiveBtConnectState: receiveBtConnectState,
      receiveBtFind: receiveBtFind,
      receiveBtScanState: receiveBtScanState,);
  }

  void receiveBtReadMsg(BluetoothMsg btMsg) {
    print("接受到的蓝牙数据：${btMsg.msg}");
  }

  void receiveBtState(BluetoothMsg btMsg) {
    bluetoothNotifier.bluetoothState = btMsg.state;
    bluetoothNotifier.connectedBluetooth = null;
  }

  void receiveBtConnectState(BluetoothMsg btMsg) {
    refreshConnectedState(btMsg);
  }

  refreshConnectedState(BluetoothMsg bluetoothMsg) {
    switch (bluetoothMsg.connectedState) {
      case BluetoothMsg.CONNECT_STATE_CONNECTED:
        bluetoothNotifier.connectedBluetooth = bluetoothMsg;
        ToastUtil.show("蓝牙连接成功");
        FlutterBluetooth.readyRead();
        break;
      case BluetoothMsg.CONNECT_STATE_FAIL:
        bluetoothNotifier.connectedBluetooth = null;
        ToastUtil.show("蓝牙连接失败，请重试");
        break;
      case BluetoothMsg.CONNECT_STATE_UNCONNECT:
        bluetoothNotifier.connectedBluetooth = null;
        ToastUtil.show("蓝牙已断开");
        break;
    }
  }

  void receiveBtFind(BluetoothMsg btMsg) {
    bluetoothListNotifier.add(btMsg);
//    if (btMsg.address == lastConnectedBlue) {
//      connectBluetooth(btMsg);
//    }
  }

  void receiveBtScanState(BluetoothMsg btMsg) {
    if (btMsg.scanState == BluetoothMsg.SCAN_STATE_START) {
      bluetoothListNotifier.clear();
      ToastUtil.show("蓝牙扫描中...");
    } else {
    }
  }


  void requestPermission() async {
    await Permission.locationAlways.request();
    await Permission.storage.request();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    FlutterBluetooth.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              BluetoothButton(bluetoothNotifier, bluetoothListNotifier, connectBluetooth, btOnColor: Colors.black,)
            ],
          ),
        ),
      ),
    );
  }

  connectBluetooth(BluetoothMsg bluetoothMsg) async {
    ToastUtil.show("蓝牙连接中...");
    await Future.delayed(Duration(milliseconds: 300));
    FlutterBluetooth.connect(bluetoothMsg);
  }
}
